package pers.w.chaptertalk.ui.me;

import androidx.appcompat.app.AppCompatActivity;

import android.os.Bundle;
import android.widget.Button;
import android.widget.ListView;
import android.widget.SimpleAdapter;

import java.io.File;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;

import pers.w.chaptertalk.R;
import pers.w.chaptertalk.funs.BookInfo;
import pers.w.chaptertalk.funs.db.Tab_Book;

public class LookCacheActivity extends AppCompatActivity {
    private SimpleAdapter adapter;
    private List<Map<String,String>> items;
    private List<BookInfo> books;
    static String BOOKNAME="bookName",PROGRESS = "progress";
   private Tab_Book tab_book;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_look_cache);
        items =new ArrayList<>();


        tab_book = new Tab_Book(this);
         books = tab_book.get_books();


        adapter = new SimpleAdapter(this, items,
                android.R.layout.simple_list_item_2,
                new String[]{BOOKNAME,PROGRESS},
                new int[]{android.R.id.text1,android.R.id.text2});

        fillItems();
        ListView lv_cache = findViewById(R.id.lv_cache);
        lv_cache.setAdapter(adapter);

        Button btn_refresh = findViewById(R.id.btn_refresh_cache);
        btn_refresh.setOnClickListener(v->fillItems());
    }

    @Override
    protected void onDestroy() {
        tab_book.close();
        super.onDestroy();
    }

    private void fillItems(){
        items.clear();
        HashMap<String,String> item;
        File bookDir;
        for (BookInfo book : books){
            item = new HashMap<>();
            item.put(BOOKNAME,book.getFieldValue(R.string.info_name));
            bookDir =book.getBookDir();
            int curCount= Objects.requireNonNull(bookDir.list()).length;
            int sqlCount = tab_book.getTab_chapter().getChapterCount(book.getID());

            item.put(PROGRESS,"当前缓存状态："+curCount + "/" + sqlCount);
            items.add(item);
        }
        adapter.notifyDataSetChanged();
    }
}
